package com.btpj.springsecuritystudy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Spring Security的配置类
 *
 * @author BTPJ  2020/8/7
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //  super.configure(auth);
        auth.inMemoryAuthentication()
                // 内存中设置用户密码，多个用and相连
                .withUser("BTPJ").password("9191").roles("user")
                .and()
                .withUser("LTP").password("1991").roles("admin");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html") // 自定义登录页面
                .loginProcessingUrl("/doLogin") // 自定义登录提交URL
                .usernameParameter("userName") // 修改用户名提交参数
                .passwordParameter("pwd") // 修改用户名提交参数
                .permitAll()
                .and()
                .csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // static下的login静态资源去除权限拦截
//        web.ignoring().antMatchers("/login/**");
    }
}
